<template>
    <div class="matchSummarize common-layout">
        <el-container class="container-box">
            <el-main class="container-main">
                <el-button :size="componentSize" type="primary" @click="start">刷新</el-button>
                <el-button :size="componentSize" type="primary" @click="addMatchSummarize"
                    :disabled="!hasEditPermission">填写我的总结</el-button>
                <!--  row-class-name="cursor-pointer" @row-click="showDetail" table-layout="auto"-->
                <el-table :size="componentSize" v-loading="loading" :data="matchSummarize" :row-class-name="rowClassName"
                    @row-click="showDetail">
                    <template v-slot:empty>
                        <el-empty image="https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/image/ojSass-empty.png" />
                    </template>
                    <el-table-column prop="user.name" label="成员" width="" show-overflow-tooltip>
                        <template #default="{ row }">
                            {{ row?.user?.xingming ? `${row?.user?.xingming} (${row?.user?.name})` : row?.user?.name }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="createdAt" label="发表时间" width="" show-overflow-tooltip
                        :formatter="({ createdAt }) => TimeYH(createdAt)">
                    </el-table-column>
                    <el-table-column prop="questionnum" label="总结题目数" width="">
                    </el-table-column>
                    <el-table-column fixed="right" width="100" label="操作">
                        <template #default="{ row }">
                            <el-button :size="componentSize" type="primary" :disabled="getWatchPermisiion(row)"
                                @click.stop="showDetail(row)">
                                {{ user?.ID === row.userid ? "编辑" : "查看" }}
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <!-- 分页 -->
                <el-pagination class="pager" :size="componentSize" :page-size="limit" :total="totalCount"
                    @current-change="changePage" layout="total,prev, pager, next"
                    :current-page="Math.floor(offset / limit) + 1">
                </el-pagination>
            </el-main>
            <el-aside class="container-aside" v-if="!isCollapse" v-loading="detailLoading" :collapsible="isCollapse"
                :width="isCollapse ? '0px' : '60%'">
                <el-scrollbar>
                    <el-menu :collapse="isCollapse">
                        <div class="right-question-summarize-box margin-bottom20">
                            <div class="right-question-summarize">
                                <strong>
                                    <el-text type="primary">{{ `${selectedRow?.user?.name || ''}` }}</el-text>
                                    总结
                                </strong>
                                <el-button @click="isCollapse = true" :size="componentSize" type="" text>
                                    <el-icon>
                                        <Close />
                                    </el-icon>
                                </el-button>
                            </div>
                            <el-table :cell-class-name="cellClassName" :data="matchSummarizeUser" max-height="50vh">
                                <template v-slot:empty>
                                    <el-empty
                                        image="https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/image/ojSass-empty.png" />
                                </template>
                                <el-table-column type="index" prop="" label="序号" width="60"
                                    align="center"></el-table-column>
                                <el-table-column prop="questionname" label="题目名" width="120"
                                    show-overflow-tooltip></el-table-column>
                                <el-table-column prop="score" label="满分" width="80" align="center"></el-table-column>
                                <el-table-column prop="df" label="比赛得分" width="90" align="center">
                                    <template #default="{ row }">
                                        <div :class="scoreClassName(row.df, row.score)">
                                            {{ row.df }}
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="practiseDf" label="补题得分" width="90" align="center">
                                    <template #default="{ row }">
                                        <div :class="scoreClassName(row.practiseDf, row.score)">
                                            {{ row.practiseDf }}
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="oldId" label="赛后补题" width="90">
                                    <template #default="{ row }">
                                        <div>
                                            <span v-if="isWatch" :size="componentSize"
                                                :type="row.canPractise ? 'primary' : 'info'" :plain="!row.canPractise">
                                                {{ !row.canPractise ? row.questionType : (row.hasPractise ? '已补题' :
                                                    '未补题')
                                                }}
                                            </span>
                                            <el-button v-else :size="componentSize" :disabled="!row.canPractise"
                                                :type="row.canPractise ? 'primary' : 'info'" :plain="!row.canPractise"
                                                @click="toQuestion(row)">
                                                {{ row.questionType === '代码' ? '补题' : row.questionType }}
                                            </el-button>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="context" label="题目总结">
                                    <template #default="{ row }">
                                        <div>
                                            <el-text v-if="isWatch" type="" :size="componentSize" class=""
                                                v-text="row.context">
                                            </el-text>
                                            <el-input v-else class="" :size="componentSize" placeholder="填写题目总结"
                                                maxlength="500" show-word-limit v-model="row.context"
                                                :autosize="{ minRows: 2 }" type="textarea" />
                                        </div>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                        <div class="right-match-experience-box">
                            <div class="">
                                <b>心得体会</b>
                            </div>
                            <div class="right-match-experience">
                                <el-text v-if="isWatch" type="" :size="componentSize" class="" v-text="context">
                                </el-text>
                                <el-input v-else class="" :size="componentSize" placeholder="填写比赛总结" maxlength="10000"
                                    show-word-limit v-model="context" :autosize="{ minRows: 4 }" type="textarea" />
                            </div>
                            <el-button v-if="hasEditPermission && !isWatch" :size="componentSize" type="primary"
                                @click="submit">
                                提交
                            </el-button>
                        </div>
                    </el-menu>
                </el-scrollbar>
            </el-aside>
        </el-container>
    </div>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus';
import { Close } from '@element-plus/icons-vue';
import { computed, onMounted, ref, watch } from 'vue';
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import { Iobj, asyncCreatematchsummary, asyncGetmatchsummary, asyncSelectmatchsummary, asyncselectmatchquestion, asyncselectmatchranking, selectteamrole } from "../api";
import { Storekey } from "../interface";
import Studycodemodel from "../mysql_interface/studycodemodel";
import { TimeYH, delay } from "../util/time";

interface MatchSummarizeProps {
    match: Studycodemodel.Iactivity
    size?: 'small' | 'default' | 'large'
    useRankingLogic?: boolean // 是否使用排行榜逻辑，false 则总是显示成绩
}

const p = defineProps<MatchSummarizeProps>()

// 设置默认值
const componentSize = computed(() => p.size || 'default')
const shouldUseRankingLogic = computed(() => p.useRankingLogic !== false) // 默认为 true

const router = useRouter();
const store = useStore(Storekey)
const user = computed(() => {
    return store.state.user
})
const teamId = computed(() => {
    return user.value?.teamid
})
const format = computed(() => {
    return p.match.format
})
watch(() => p.match.ID, (v) => {
    if (v) start()
})
const match = computed(() => {
    return p.match
})
const activityuser = computed(() => {
    return p.match.activityuser || []
})
onMounted(() => {
    start()
})

const loading = ref(false)
// 右侧aside展开详情
const detailLoading = ref(false)
const isCollapse = ref(true)
// 比赛总结
const context = ref("")
// 题目总结
const matchSummarizeUser = ref<Studycodemodel.Imatchsummaryuser[]>([])
// 答题记录
const answerRecords = ref<Studycodemodel.Imatchquestion[]>([])
// 比赛题目赛后练习记录
const userQuestion = ref<Studycodemodel.Iuserquestion[]>([])

const limit = ref(20)
const offset = ref(0)
const totalCount = ref<number>(0)
const matchSummarize = ref<Studycodemodel.Imatchsummary[]>([])
const matchQuestion = ref<Studycodemodel.Imatchquestion[]>([])
async function start() {
    loading.value = true
    let cond: Iobj<Studycodemodel.Imatchsummary> = { activityid: match.value.ID, _limit: limit.value, _offset: offset.value }
    // 过滤参赛选手
    if (!user.value?.isAdmin && activityuser.value.length) {
        const uids = activityuser.value.map(e => e.userid)
        cond.userid = uids
    }
    const { rows, count, userquestion } = await asyncSelectmatchsummary(cond) as any
    matchSummarize.value = rows || []
    totalCount.value = count
    userQuestion.value = userquestion || []
    // 比赛题目
    const [{ matchquestion }] = await asyncselectmatchquestion({ activityid: match.value.ID! })
    matchQuestion.value = matchquestion || []
    // 答题记录
    let { matchranking: rank } = await asyncselectmatchranking({
        activityid: match.value.ID,
        _offset: offset.value, _limit: limit.value, _order: 'df', _sortable: 'DESC'
    })
    answerRecords.value = rank
    // 权限
    await getPermissionsCfg()
    loading.value = false
    // 
    if (selectedRow.value) {
        showDetail(selectedRow.value)
    }
}

// 获取权限
const roleName = "学生"
const routerNames = ref<any[]>([])
async function getPermissionsCfg() {
    const { count, rows } = await selectteamrole({ teamid: user.value?.teamid, name: roleName })
    // 可能存在多条
    routerNames.value = rows[0]?.routername || []
}
// 编辑权限
const hasEditPermission = computed(() => {
    let activityUserPm = true
    if (activityuser.value.length) {
        activityUserPm = !!activityuser.value.find(e => e.userid === user.value?.ID)
    }
    let myMatchRet = !!answerRecords.value.find(e => e.userid === user.value?.ID)
    // console.log("matchSummarize activityUserPm=>", activityUserPm, "myMatchRet=>", myMatchRet)
    return activityUserPm && myMatchRet
})
// 查看权限
const routerPm = computed(() => {
    let ret = false
    // 老师都能看 user.value?.isAdmin ||
    if (user.value?.isAdmin || !!routerNames.value.find(e => e === "比赛总结")) {
        ret = true
    }
    return ret
})
function getWatchPermisiion(row: Studycodemodel.Imatchsummary) {
    let disabled = false;
    if (routerPm.value) {
        return disabled
    }
    // 点击自己 false
    disabled = user.value?.ID !== row.userid
    return disabled
}

// 添加我的
async function addMatchSummarize() {
    isCollapse.value = false
    // 每个人单个比赛只有一条总结
    detailLoading.value = true
    selectedRow.value = {
        userid: user.value?.ID,
        user: { ID: user.value?.ID, name: user.value?.name }
    } as Studycodemodel.Imatchsummary
    try {
        selectedRow.value = await asyncGetmatchsummary({ activityid: match.value.ID, userid: user.value?.ID })
    } catch (error) {
        console.error("asyncGetmatchsummary", error)
    }
    detailLoading.value = false
    showDetail(selectedRow.value)
}

// 编辑-展开详情
const selectedRow = ref<Studycodemodel.Imatchsummary>({});
const isWatch = ref(false)
async function showDetail(row: Studycodemodel.Imatchsummary) {
    if (getWatchPermisiion(row)) {
        return
    }
    isCollapse.value = false
    selectedRow.value = row
    matchSummarizeUser.value = row.matchsummaryuser || []
    context.value = row.context || "暂未填写"
    // 详情的userid与登录者userid不一样 不能编辑
    isWatch.value = user.value?.ID !== row.userid

    // 第一次写总结
    // if (!row.matchsummaryuser?.length) {
    detailLoading.value = true
    await delay(100);
    await formatMatchSummaryUser(row)
    detailLoading.value = false
    // }
}

// 成绩
async function formatMatchSummaryUser(matchSummary: Studycodemodel.Imatchsummary) {
    const userId = matchSummary.userid
    // 详情的userid与登录者userid不一样 不能编辑
    isWatch.value = user.value?.ID !== userId
    // 答题记录
    let userAnswerRecords = answerRecords.value.filter(e => e.userid === userId)
    // 组装数据
    formatQuestionScore(matchQuestion.value || [], userAnswerRecords)
}
// format question-score
function formatQuestionScore(matchQuestion: Studycodemodel.Imatchquestion[], userAnswerRecords: Studycodemodel.Imatchranking[]) {
    let userAnswerRecord = userAnswerRecords[0]
    // [[type, df, name, ac],[...]]
    const _matchrankingData = JSON.parse(userAnswerRecord?.data || '[]') as any[]
    matchSummarizeUser.value = matchQuestion.map(e => {
        // 根据 useRankingLogic 决定是否使用排行榜逻辑
        const answered = shouldUseRankingLogic.value 
            ? (match.value.isranking ? _matchrankingData.find(z => z[2] === e.name) : [, "-"])
            : _matchrankingData.find(z => z[2] === e.name)
        
        // 总结记录-userID  必须先总结才能补题
        const summarizeUser = matchSummarizeUser.value.find(z => z.questionid === e.ID) || { userid: undefined }
        // 练习记录
        const practiseRet = userQuestion.value.find(z => z.questionid === e.oldid && z.userid === summarizeUser.userid)
        const hasPractise = practiseRet ? true : false
        const canPractise = e.type === '代码'
        return {
            activityid: match.value.ID,
            userid: userAnswerRecord?.userid,
            oldId: e.oldid, // 题库题目ID
            questionid: e.ID, // 比赛题目ID
            questionname: e.name,
            df: answered ? answered[1] || 0 : '-', // 比赛得分
            answered,
            questionType: e.type,
            canPractise: canPractise,
            // 补题得分 报错的时候 df:null 
            practiseDf: hasPractise ? (practiseRet?.df || 0) : (canPractise ? '未补题' : '-'),
            hasPractise: hasPractise,
            score: e.score,
            context: summarizeUser?.context || "",
        }
    })
    // context.value = ""

    // 没有比赛答题记录，不可以提交总结
    if (!userAnswerRecord) {
        isWatch.value = true
        return
    }
}

function rowClassName({ row, rowIndex }: { row: any, rowIndex: number }): string {
    let className = 'cursor-pointer'
    if (selectedRow.value == row) {
        className = 'highlight-row cursor-pointer'; // 
    }
    return className;
};
function changePage(r: number) {
    offset.value = (r - 1) * limit.value
    start()
}
// 分数列添加背景颜色
function cellClassName(data: { row: any, column: any, rowIndex: number, columnIndex: number }): string {
    if (data.columnIndex === 0 || data.columnIndex === 1 || data.columnIndex === 2 || data.columnIndex === 3) {
        return "cell-score"
    }
    return ""
}
// 比赛得分、补题得分
function scoreClassName(df: number, score: number) {
    if (isNaN(df)) {
        return
    }
    if (df >= score) {
        return 'Accepted'
    } else if (df > 0) {
        return 'Unaccepted'
    } else {
        return 'CompileError'
    }
}
// 补题-新开标签页
function toQuestion(row: any) {
    const url = router.resolve({
        name: '题目',
        params: { ID: row.oldId },
        query: {
            teamid: teamId.value,
            activityid: match.value.ID,
            offset: offset.value,
            limit: limit.value,
        },
    })
    window.open(url.href, '_blank')
}
// 提交
async function submit() {
    let questionnum = matchSummarizeUser.value.filter(e => e.context).length
    const data = {
        ID: selectedRow.value.ID,
        matchsummaryuser: matchSummarizeUser.value,
        context: context.value,
        activityid: match.value.ID,
        userid: user.value?.ID,
        questionnum
    }
    // 如果全部为空，点提交的时候提示"您尚未填写总结内容"
    if (!context.value && !questionnum) {
        ElMessage.error("您尚未填写总结内容")
        return
    }
    try {
        detailLoading.value = true
        await asyncCreatematchsummary(data)
        detailLoading.value = false
        ElMessage.success("操作成功");
        start()
    } catch (e: any) {
        ElMessage.error(e);
    }
}
</script>

<style scoped>
.container-box {
    --container-margin: 20px;
    --container-header-height: 7vh;
    --container-bg-color: #fff;
    height: auto;
}

.container-main {
    padding: 0px;
    /* !!! */
    overflow: hidden;
    /* margin-right: var(--container-margin);
    padding-right: var(--container-margin);
    border-right: 1px solid #ccc; */
}

.container-aside {
    background: var(--container-bg-color);
    margin-left: var(--container-margin);
    padding-left: var(--container-margin);
    border-left: 1px solid #ccc;
    border-radius: 0 !important;
    box-shadow: none !important;
}

.right-question-summarize {
    height: 32px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.right-match-experience {
    margin: 10px 0 15px 0;
}

.container-content .pager {
    margin: var(--container-margin);
    margin-right: 0;
    margin-bottom: 0;
    float: right;
}

.btn {
    width: 70px;
}
</style>
<style>
#app.ojSass .matchSummarize .container-aside .el-menu {
    border: none;
}

#app.ojSass .matchSummarize .container-aside .cell-score {
    background-color: #fafafa;
}
</style>
